package com.desire.redis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;

@SpringBootTest
public class Redis_BitMap_OnlineStatistics {
    private static final int user01 = 1;
    private static final int user02 = 2;
    private static final int user03 = 3;
    private static final String key20220601 = "20200601";
    private static final String key20220602 = "20200602";
    private static final String key20220603 = "20200603";
    private static final String saveKey = "20200601#20200602#20200603";
    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> valueOperations;
    @Autowired(required = false)
    private StringRedisTemplate redisTemplate;

    @Test
    void tt() {
        // 在6月1号  来了两个 user01 user02
        valueOperations.setBit(key20220601, user01, true);
        valueOperations.setBit(key20220601, user02, true);
        valueOperations.setBit(key20220601, user03, true);
        // 在6月2号  来了一个 user02
        valueOperations.setBit(key20220602, user02, true);
        valueOperations.setBit(key20220602, user03, true);
        // 在6月3号  来了两个 user02 user03
        valueOperations.setBit(key20220603, user02, true);
        valueOperations.setBit(key20220603, user03, true);


        // 现在统计 三天内 都来的人数
        RedisCallback<Long> callback = connection -> connection.bitOp(
                RedisStringCommands.BitOperation.AND,
                saveKey.getBytes(),
                key20220601.getBytes(), key20220602.getBytes(), key20220603.getBytes());
        // value 值 代表了 元数据 即返回 0 代表失败 , 1 代表成功
        Long value = redisTemplate.execute(callback);
        System.out.println(value);

        RedisCallback<Long> callback2 = connection -> connection.bitCount(saveKey.getBytes());
        // value2 代表 了 使用BitOperation的and 取交集的 得出的结果值，即三天内，都来的人数 此时 0代表没有人天天来，1代表有一人，代表有两人，3代表有三人
        Long value2 = redisTemplate.execute(callback2);
        System.out.println("来了" + value2);

    }
}
